@file:OptIn(ExperimentalMaterial3Api::class)

package com.example.myapplication5.ui.screens

import android.annotation.SuppressLint
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.myapplication5.viewmodel.EditorViewModel
import com.example.myapplication5.viewmodel.factory.TodoViewModelFactory

@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun EditorScreen(
    id: String, editorViewModel: EditorViewModel = viewModel(
        factory = TodoViewModelFactory(
            LocalContext.current
        )
    ), onPop: () -> Unit
) {
    val toast = editorViewModel.toast
    val lifecycleOwner = LocalLifecycleOwner.current
    val context = LocalContext.current

    LaunchedEffect(key1 = Unit) {
        editorViewModel.fetch(id)
    }
    LaunchedEffect(key1 = toast, key2 = lifecycleOwner) {
        lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
            toast.collect {
                Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
            }
        }
    }
    Scaffold(topBar = {
        TopAppBar(title = { Text("Editor") }, navigationIcon = {
            IconButton(onClick = { onPop() }) {
                Icon(imageVector = Icons.Default.ArrowBack, contentDescription = null)
            }
        }, actions = {
            TextButton(onClick = { editorViewModel.onSave() }) {
                Text(text = "Save")
            }
        })
    }) {
        TextField(
            value = editorViewModel.todo.content, onValueChange = {
                editorViewModel.onValueChange(it)
            }, modifier = Modifier
                .fillMaxSize()
                .padding(top = it.calculateTopPadding())
        )


    }
}